package cn.life.common.support.check;

import cn.life.common.entity.model.CMessage;
import cn.life.common.entity.model.MyCommon;
import cn.life.common.test.Test;
import cn.life.common.utils.BodyReaderHttpServletRequestWrapper;
import cn.life.common.utils.EncryptPwdUtil;
import cn.life.common.utils.JwtUtil;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

/**
 * @Description:    用户信息拦截器
 *
 * @Author 李佳明
 * @Date 2018/7/17 0017 下午 1:45
 */
public class UserInterceptorHandler implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(UserInterceptorHandler.class);

    /** 登录用户信息session中的key */
    private String sessionKey = MyCommon.MY_SESSION_KEY;

    public static void main(String[] args){
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Param Start<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        logger.debug("context");
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Param End<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        request.setCharacterEncoding("UTF-8");

        response.setHeader("Access-Control-Allow-Origin", "*"); //解决跨域访问报错
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600"); //设置过期时间
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // 支持HTTP 1.1.
        response.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0. response.setHeader("Expires", "0");

        String contentType = request.getContentType();

        System.out.println(contentType);
        if(contentType != null && !contentType.equals("application/x-www-form-urlencoded")){
            ServletRequest requestWrapper = null;
            if(request instanceof HttpServletRequest) {
                requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
            }
            String param= null;
            BufferedReader streamReader = new BufferedReader( new InputStreamReader(requestWrapper.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);
        }

        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("factoryCookie")){
                    sessionKey = cookie.getValue();
                }
            }
        }

        // 获取session中存放的用户信息
        Object sessionMember = WebUtils.getSessionAttribute(request, sessionKey);
        if(sessionMember != null){
            return true;
        }

        String token = request.getHeader("token");
        if(request.getServletPath().contains("go_to_") || request.getServletPath().contains("web/")|| request.getServletPath().contains("login")|| request.getServletPath().contains("adminLogin")){
            return true;
        }
        if(null == token){
            writeJson(response,CMessage.fail("1001","当前用户信息已失效，请重新登录"));
            return false;
        }else{
            Claims claims = JwtUtil.verifyToken(token);
            if(claims == null){
                writeJson(response,CMessage.fail("1001","当前用户信息已失效，请重新登录"));
                return false;
            }
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    /**
     * 输出Json
     *
     * @param response
     * @param obj
     */
    public void writeJson(HttpServletResponse response, Object obj) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(JSONObject.toJSONString(obj));
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
